package com.study.goal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.common.core.domain.PageQuery;
import com.study.common.core.page.TableDataInfo;
import com.study.goal.domain.Goal;
import com.study.goal.domain.GoalAssignment;
import com.study.goal.domain.bo.GoalAssignmentBo;
import com.study.goal.domain.vo.GoalAssignmentVo;
import com.study.goal.domain.vo.GoalVo;
import com.study.goal.mapper.GoalAssignmentMapper;
import com.study.goal.mapper.GoalsMapper;
import com.study.goal.service.GoalAssignmentService;
import com.study.goal.service.IPlanOccurrenceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@RequiredArgsConstructor
@Service
public class GoalAssignmentServiceImpl implements GoalAssignmentService {

    private final GoalAssignmentMapper baseMapper;

    private final GoalsMapper goalsMapper;

    private final IPlanOccurrenceService planOccurrenceService;

    @Override
    public TableDataInfo<GoalAssignmentVo> queryPageList(GoalAssignmentBo bo, PageQuery pageQuery) {
        //分页查询列表
        LambdaQueryWrapper<GoalAssignment> lqw = buildQueryWrapper(bo);
        Page<GoalAssignmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(GoalAssignmentBo bo, boolean cascade) {
        // 1. 保存分配记录
        GoalAssignment entity = BeanUtil.toBean(bo, GoalAssignment.class);
        entity.setStatus("ASSIGNED");
        entity.setAssignTime(new Date());
        int insertResult = baseMapper.insert(entity);

        if (insertResult > 0) {
            // 2. 更新目标状态
            Long goalId = bo.getGoalId();

            // 更新当前目标为 ASSIGNED
            goalsMapper.update(null, new LambdaUpdateWrapper<Goal>()
                    .eq(Goal::getId, goalId)
                    .set(Goal::getStatus, "ASSIGNED"));

            // 3. 可选：级联更新子目标（如果以后有需求）
            if (Boolean.TRUE.equals(cascade)) {
                updateChildGoalsStatus(goalId, "ASSIGNED");
            }

            // 4. 生成计划 occurrence
            planOccurrenceService.generateOccurrencesForAssignment(entity.getId(), true, 7);

        }
        return insertResult > 0;
    }

    @Override
    public Boolean updateByBo(GoalAssignmentBo bo) {
        GoalAssignment goalAssignment = BeanUtil.toBean(bo, GoalAssignment.class);
        goalAssignment.setUpdateTime(new Date());
        return baseMapper.updateById(goalAssignment) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Long id, Boolean isValid) {
        return baseMapper.deleteById(id) > 0;
    }

    private LambdaQueryWrapper<GoalAssignment> buildQueryWrapper(GoalAssignmentBo bo) {
        LambdaQueryWrapper<GoalAssignment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getGuardianId() != null, GoalAssignment::getGuardianId, bo.getGuardianId())
                .eq(bo.getStudentId() != null, GoalAssignment::getStudentId, bo.getStudentId())
                .eq(bo.getGoalId() != null, GoalAssignment::getGoalId, bo.getGoalId());
        return lqw;
    }


    /**
     * 递归更新子目标的状态
     */
    private void updateChildGoalsStatus(Long parentId, String status) {
        List<Goal> childGoals = goalsMapper.selectList(new LambdaQueryWrapper<Goal>()
                .eq(Goal::getParentId, parentId));

        if (childGoals != null && !childGoals.isEmpty()) {
            for (Goal child : childGoals) {
                goalsMapper.update(null, new LambdaUpdateWrapper<Goal>()
                        .eq(Goal::getId, child.getId())
                        .set(Goal::getStatus, status));
                // 递归处理更下一级
                updateChildGoalsStatus(child.getId(), status);
            }
        }
    }
}
